package top.withwings.bonus.common.repo;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import top.withwings.bonus.common.pojo.User;

import java.util.List;

@Repository
public class UserRepo {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private NamedParameterJdbcTemplate namedJdbcTemplate;

    public int create(User user) {
        String sql = "insert into user(username,password,realname) values (:username,:password,:realname)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        namedJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(user), keyHolder);
        return keyHolder.getKey().intValue();
    }


    public void update(User user) {
        String sql = " update user set username = :username, password=:password, realname =:realname,enabled=:enabled where id =:id";
        namedJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(user));
    }


    public void delete(int userId) {
        String sql = "delete from user where id = ?";
        jdbcTemplate.update(sql, userId);
    }

    public List<User> findAll() {
        String sql = " select id , username ,realname,password,enabled from user";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class));
    }

    public User findById(int userId) {
        String sql = " select id , username ,realname,password,enabled from user where id = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), userId);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public User findByUsername(String username) {
        String sql = " select id , username ,realname,password,enabled from user where username = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }



}
